package com.kcs.fxmargin.action;

import java.util.List;

import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.bo.LoginBO;
import com.kcs.fxmargin.service.LoginService;
import com.kcs.fxmargin.service.UsersService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.*;

public class LoginAction extends FXAction
{
	
	private Logger log = Logger.getLogger(Constant.LOG_FX);

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        LoginActionForm bean = null;
        LoginService svc = null;
        LoginBO bo = null;

        log.info("Begin : LoginAction : execute");
        
        try{
        	
        	bean = (LoginActionForm)form;
        	log.info(">>TranCode : "+bean.getTranCode());
        	
        	if(bean.getTranCode().equals("authenticateUser")){
        		log.info("authenticateUser : "+bean.getUserId());

                svc = new LoginService();
                
            	//Get User Data
                if(validateGetUserData(bean,request)){
                	bo = new LoginBO();
                    bo.setUserId(bean.getUserId());
                    bo.setPassword(bean.getPassword());
                    
                    bo = svc.getUserData(bo);
                    
                    log.info("resultAuthen : "+bo.isResultAuthen());
                    log.info("viaLDAP : "+bo.getViaLdap());
                    
                    if(bo.isResultAuthen()){
                    	
                    	//LDAP
                    	if(bo.getViaLdap().equals("1")){
                    		bo = svc.authenticateUserLDAP(bo);
                    		
                    	}else{
                    		bo.setResultLdap(true);
                    	}
                    	
                    	log.info("resultLDAP : "+bo.isResultLdap());
                    	
                    	if(bo.isResultLdap()){
		                    bean.setRoleId(bo.getRoleId());
		                    bean.setUserName(bo.getUserName());
		                    String loginData = getLoginDataHTML(bean);
		                    request.setAttribute(Constant.LOGIN_DATA_ATTR, loginData);
		                    
		                    //Session
		                    request.getSession().setAttribute(Constant.LOGIN_DATA_SESSION, bean);
		                    
		                    log.info("> userId : "+bo.getUserId());
		                    log.info("> userName : "+bo.getUserName());
		                    log.info("> roleId : "+bo.getRoleId());
		                    
		                    //Get Menu List
		                    if(validateGetMenuList(bo, request))
		                    {
		                    	bo = svc.getMenuList(bo);
		                    	String headerMenu = getHeaderMenuHTML(bo.getMenuList());
		
		                    	request.setAttribute(Constant.HEADER_MENU_ATTR, headerMenu);
		                    	
		                    	//Session
		                        request.getSession().setAttribute(Constant.HEADER_MENU_SESSION, headerMenu);
		                        
		                        String sessionId = request.getSession().getId();
		                        
		                        log.info("Login sessionId = " + sessionId);
		                        
		                        UsersService user = new UsersService();
		                        user.loginUpdateUser(bo.getUserId(), sessionId);
		                        
		                        return mapping.findForward("mainPage");
		                    }  
                    	}else{
                    		request.setAttribute(Constant.ERR_ATTR, "msg00023");
                    	}
                    
                    }else{
                    	request.setAttribute(Constant.ERR_ATTR, Constant.ERR_USER_NOT_FOUND);
                    }
                   
                }

        	}
        		
        	
        }catch(Exception e){
        	e.printStackTrace();
        	request.setAttribute(Constant.ERR_ATTR, e+"");
        }finally{
        	bean.setTranCode("");
        }
        
        log.info("End : LoginAction : execute");
        
        return mapping.findForward("login");
    }

	@Override
	public ActionForward process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
    
    private boolean validateAuthenticateUser(LoginActionForm bean, HttpServletRequest request)
    {
        if(bean.getUserId().equals(""))
        {
            request.setAttribute("error", "User ID is empty!");
            return false;
        }
        if(bean.getPassword().equals(""))
        {
            request.setAttribute("error", "Password is empty!");
            return false;
        } else
        {
            return true;
        }
    }
    
    private boolean validateGetUserData(LoginActionForm bean, HttpServletRequest request) {
    	boolean result = true;
		if (bean.getUserId().equals("")) {
			request.setAttribute(Constant.ERR_ATTR, "msg00021");
			result = false;
		}
		
		if (bean.getPassword().equals("")) {
			request.setAttribute(Constant.ERR_ATTR, "msg00022");
			result = false;
		}
		
		return result;
	}
    
    private boolean validateGetMenuList(LoginBO bo, HttpServletRequest request) {
		if (bo.getRoleId().equals("")) {
			request.setAttribute(Constant.ERR_ATTR, Constant.ERR_ROLE_ID_EMPTY);
			return false;
		} else {
			return true;
		}
	}
	
	public String getHeaderMenuHTML(List<LoginBO> menuList)throws Exception{
		String result = null;
		
		result = "<div id='divFXMenu'><ul class='fxCssMenu fxCssMenum0'>";
		result += "<li class='fxCssMenui0'><a class='fxCssMenui0' href='/FxMargin/MainPageAction.do'>Home</a></li>";
		
		for(int i=0; i<menuList.size(); i++){
			LoginBO m = menuList.get(i);
			
			//-- menu
			if((m.getMlParentMenu().equals("null") && countChilds(m.getMlId(),menuList)>0) || m.getMlParentMenu().equals("")){
				result += "<li class='fxCssMenui0'><a class='fxCssMenui0' href='"+m.getMlUrl()+"'>" + m.getMlName() +"</a><ul class='fxCssMenum'>";
				
					for(int j=0; j<menuList.size(); j++){
						LoginBO m2 = menuList.get(j);
						
						//-- sub menu
						if(m2.getMlParentMenu().equals(m.getMlId())){
							result += "<li class='fxCssMenum'><a class='fxCssMenum' href='"+m2.getMlUrl()+"'>"+m2.getMlName()+"</a></li>";
						}
					}
					
				result += "</ul></li>";
			}
			
		}
		
		result +=" </ul></div>";
		
		return result;
	}
	
	private int countChilds(String mlId, List<LoginBO> menuList)throws Exception{
		int count = 0;
		for(int i=0; i<menuList.size(); i++){
			LoginBO m = menuList.get(i);
			if(m.getMlParentMenu().equals(mlId)){
				count++;
			}
		}
		
		return count;
	}
}